/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
//rem
(function (doc, win) {
	var docEl = doc.documentElement,
		resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
		recalc = function () {
			var clientWidth = docEl.clientWidth;
			if (!clientWidth) return;
			if(clientWidth>=750){
				docEl.style.fontSize = '100px';
			}else{
				docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
			}
		};

	if (!doc.addEventListener) return;
	win.addEventListener(resizeEvt, recalc, false);
	doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

//用户设备 1安卓，2ios
function ismobile(test){
			    var u = navigator.userAgent, app = navigator.appVersion;
			    if(/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))){
			     if(window.location.href.indexOf("?mobile")<0){
			      try{
			       if(/iPhone|mac|iPod|iPad/i.test(navigator.userAgent)){
			        return '0';
			       }else{
			        return '1';
			       }
			      }catch(e){}
			     }
			    }else if( u.indexOf('iPad') > -1){
			        return '0';
			    }else{
			        return '1';
			    }
			};
(function($, owner) {
	/**
	 * 用户登录
	 **/
	
	//童伴测试地址
	//Apiurl="http://tongban.weidu68.com/api/";
	
	//童伴生产地址
	Apiurl="http://tongban.weidu168.com/api/"; 
	owner.login = function(loginInfo, callback) {
		
		callback = callback || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.tel = loginInfo.tel || '';
		//console.log(loginInfo.tel);
		loginInfo.pwd = loginInfo.pwd || '';
		loginInfo.imei = plus.device.imei || '';
		if(ismobile()==0){
					loginInfo.appType = 2;
				}else{
					loginInfo.appType = 1; 
				}
		if(loginInfo.tel.length < 5) {
			return callback('账号最短为 5 个字符');
		}
		if(loginInfo.pwd.length < 6) {
			return callback('密码最短为 6 个字符');
		}
		mui.post(Apiurl+'index/login', loginInfo, function(rsp) {
			 console.log(JSON.stringify(rsp)); 
			if(rsp.id > 0) {
				if(rsp.point){
					plus.nativeUI.toast('恭喜您获得'+rsp.point+'积分', {
						verticalAlign: 'top'
					});
				}
				return owner.createState(rsp, callback);
			}else if(rsp.status==404){
				return callback('已在其他设备登录');
			} else {
				return callback('用户名或密码错误');
			}
		}, 'json');

	};
	
	
/*navigator.geolocation.getCurrentPosition( // 该函数有如下三个参数
       		 function(pos){ // 如果成果则执行该回调函数
        	var lat=pos.coords.latitude;
        	lng=pos.coords.longitude;
        	
        }, function(err){ // 如果失败则执行该回调函数
            alert(err.message);
        }, { // 附带参数
            //enableHighAccuracy: false, // 提高精度(耗费资源) 
            //timeout: 3000, // 超过timeout则调用失败的回调函数
            //maximumAge: 1000 // 获取到的地理信息的有效期，超过有效期则重新获取一次位置信息
        }
    );*/
  	owner.createState = function(data, callback) {
		console.log(JSON.stringify(data));
		var state = owner.getState(); 
		state.userid = data.id;
		state.username = data.name;
		state.childid = data.child_id;
		state.code = data.code;
		state.avatar = data.avatar;
		state.childname = data.child_name;
		
		state.age = data.age;
		state.memberToken = data.memberToken;
		state.vip = data.vip;
		state.type = data.type;
		owner.setState(state);
		return callback();
	};

	

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	var checkEmail = function(email) {
		email = email || '';
		return(email.length > 3 && email.indexOf('@') > -1);
	};
  	  

	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || $.noop;
		if(!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};

	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$settings', JSON.stringify(settings));
	}
	          	  
	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
		var settingsText = localStorage.getItem('$settings') || "{}";
		//console.log(settingsText);
		return JSON.parse(settingsText);
	}
	/**
	 * 获取本地是否安装客户端
	 **/
	owner.isInstalled = function(id) {
		if(id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if(mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch(e) {}
		} else {
			switch(id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	}
}(mui, window.app = {}));



